package cn.cque.controller;

import cn.cque.common.BaseController;
import cn.cque.entity.InfoResult;
import cn.cque.entity.User;
import cn.cque.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: XWC
 * @ClassName: UserController
 * @Date: 2020/10/4
 * @Time: 17:47
 * @Description:
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public InfoResult login(String username, String password, String verCode) {
        if (!CaptchaUtil.ver(verCode, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            return InfoResult.ERROR("验证码不正确");
        }
        CaptchaUtil.clear(request);
        //校验用户名密码
        User user = userService.login(username, password);

        if (user != null) {
            //登录成功
            request.getSession().setAttribute("loginUser", user);
            return InfoResult.SUCCESS();
        } else {
            //登录失败
            return InfoResult.ERROR("用户名或密码错误");
        }
    }

    @RequestMapping("/logout")
    public InfoResult logout(){
        //将用户信息从session中移除
        request.getSession().removeAttribute("loginUser");
        //跳转页面
        return InfoResult.SUCCESS();
    }

    @RequestMapping("/register")
    public InfoResult register(User user){
        //获取验证码
        String check = request.getParameter("check");
        //校验验证码
        if (!CaptchaUtil.ver(check, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            return InfoResult.ERROR("验证码不正确");
        }
        CaptchaUtil.clear(request);

        int s= userService.register(user);
        if (s>0){
            return InfoResult.SUCCESS("添加成功");
        }else {
            return InfoResult.ERROR("添加失败");
        }
    }
}